//
//  Number.swift
//  VPai
//
//  Created by devel on 16/10/27.
//  Copyright © 2016年 viatech. All rights reserved.
//

import Foundation

class Number {
    
    class func UInt8ToUInt32(b1: UInt8, b2: UInt8, b3: UInt8, b4: UInt8, isLittleEndian: Bool) -> UInt32{
        var ret : UInt32 = 0
        
        if (isLittleEndian) {
            ret =  ((UInt32(b4) << 24) & 0xFF000000)
            ret |= ((UInt32(b3) << 16) & 0x00FF0000)
            ret |= ((UInt32(b2) << 8) & 0x0000FF00)
            ret |= ((UInt32(b1) << 0) & 0x000000FF);
        } else {
            ret =  ((UInt32(b1) << 24) & 0xFF000000)
            ret |= ((UInt32(b2) << 16) & 0x00FF0000)
            ret |= ((UInt32(b3) << 8) & 0x0000FF00)
            ret |= ((UInt32(b4) << 0) & 0x000000FF)
        }
        
        return ret
    }
    
    class func UInt32ToUInt8Array(value: UInt32, isLittleEndian: Bool) -> [UInt8]{
        var buffer: [UInt8] = [UInt8](count: 4, repeatedValue: 0)
        if isLittleEndian {
            buffer[3] = UInt8((value & 0xFF000000) >> 24)
            buffer[2] = UInt8((value & 0x00FF0000) >> 16)
            buffer[1] = UInt8((value & 0x0000FF00) >> 8)
            buffer[0] = UInt8((value & 0x000000FF) >> 0)
        }else {
            buffer[0] = UInt8((value & 0xFF000000) >> 24)
            buffer[1] = UInt8((value & 0x00FF0000) >> 16)
            buffer[2] = UInt8((value & 0x0000FF00) >> 8)
            buffer[3] = UInt8((value & 0x000000FF) >> 0)
        }
        return buffer
    }
    
    class func isUInt8ArrayEqual(array1: [UInt8], array2: [UInt8]) -> Bool {
        if(array1.count != array2.count){
            return false
        }
        
        for (index, _) in array1.enumerate(){
            if(array1[index] != array2[index]){
                return false
            }
        }
        
        return true
    }
    
    private static let hexArray = ["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"]
    class func bytesToHex(bytes: [UInt8]) -> String {
        var result = ""
        for byte in bytes {
            result += hexArray[Int(byte >> 4)]
            result += hexArray[Int(byte & 0x0F)]
        }
        return result
    }
}